#include "mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    createinterface();
}

MainWindow::~MainWindow()
{

}

void MainWindow::openfile(const QModelIndex &index)
{
    curfile = model->filePath(index);
    QFile file(curfile);
    QTextStream inpt(&file);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
        return;
    textEdit->setPlainText(inpt.readAll());
    TextEdit->show();
}

void MainWindow::open()
{
    curdir = QFileDialog::getExistingDirectory(this, "Select Directory", "/home", QFileDialog::ShowDirsOnly);
    tree->setRootIndex(model->index(curdir));
}

void MainWindow::savefile()
{
    QFile file(curfile);
    if (!file.open(QFile::WriteOnly | QFile::Text))
        return;
    QTextStream out(&file);
    out << textEdit->toPlainText();
    return;
}

void MainWindow::createinterface()
{
    mainlay = new QVBoxLayout;
    close = new QPushButton(tr("&Close"));
    button = new QPushButton(tr("&Open"));
    tree = new QTreeView;
    TextEdit = new QWidget;
    tmain = new QVBoxLayout;
    TextEdit->setHidden(true);
    tsave = new QPushButton(tr("Save"));
    tclose = new QPushButton(tr("Close"));
    tlay = new QHBoxLayout;
    tlay->addWidget(tsave);
    tlay->addWidget(tclose);
    textEdit = new QTextEdit;
    tmain->addWidget(textEdit);
    tmain->addLayout(tlay);
    TextEdit->setLayout(tmain);
    model = new QFileSystemModel;
    model->setRootPath("/home");
    QStringList filters;
    filters << "*.txt";
    model->setNameFilterDisables(false);
    model->setNameFilters(filters);
    model->setReadOnly(true);
    tree->setModel(model);
    cwidget = new QWidget;
    mainlay->addWidget(button);
    mainlay->addWidget(tree);
    mainlay->addWidget(close);
    cwidget->setLayout(mainlay);
    setCentralWidget(cwidget);
    connect(tclose, SIGNAL(clicked()), TextEdit, SLOT(hide()));
    connect(button, SIGNAL(clicked()), this, SLOT(open()));
    connect(tsave, SIGNAL(clicked()), this, SLOT(savefile()));
    connect(tree, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(openfile(QModelIndex)));
    connect(close, SIGNAL(clicked()), this, SLOT(close()));
}
